<?php

namespace Frontend\Controllers;

use DuAdmin\Core\BaseController;
use DuAdmin\Helpers\AppHelper;
use Frontend\Forms\ResendVerificationEmailForm;
use Frontend\Forms\SignupForm;
use Frontend\Forms\VerifyEmailForm;
use InvalidArgumentException;
use Yii;
use yii\web\BadRequestHttpException;

class SignupController extends BaseController
{
    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        if (!AppHelper::getSetting('site.open-signup')) {
            return $this->goHome();
        }
        $model = new SignupForm();
        // ajax表单验证
        if (($error = $this->ajaxValidation($model)) !== false) {
            return $error;
        }
        if ($model->load(Yii::$app->request->post()) && $model->signup()) {
            return $this->render('success', ['model' => $model]);
        }

        return $this->render('index', [
            'model' => $model,
        ]);
    }

    public function actionActive()
    {
        return $this->render('active', [
            'model' => Yii::$app->user
        ]);
    }

    /**
     * Resend verification email
     *
     * @return mixed
     */
    public function actionResendVerificationEmail()
    {
        $model = new ResendVerificationEmailForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', Yii::t('theme', 'Check your email for further instructions.'));
                return $this->render('resend-verification-email-success', [
                    'model' => $model
                ]);
            }
            Yii::$app->session->setFlash('error', Yii::t('theme', 'Sorry, we are unable to resend verification email for the provided email address.'));
        }
        return $this->render('resend-verification-email', [
            'model' => $model
        ]);
    }

    /**
     * Verify email address
     *
     * @param string $token
     * @return yii\web\Response
     * @throws BadRequestHttpException
     */

    public function actionVerifyEmail($token)
    {
        try {
            $model = new VerifyEmailForm($token);
        } catch (InvalidArgumentException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
        if ($user = $model->verifyEmail()) {
            if (Yii::$app->user->login($user)) {
                Yii::$app->session->setFlash('success', Yii::t('theme', 'Your email has been confirmed!'));
                return $this->goHome();
            }
        }
        Yii::$app->session->setFlash('error', Yii::t('theme', 'Sorry, we are unable to verify your account with provided token.'));
        return $this->goHome();
    }
}
